package server

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"

	config "gitcode.com/happy-mj/happy-config"
	"github.com/mark3labs/mcp-go/mcp"
	"github.com/mark3labs/mcp-go/server"
)

type AmapRouteResponse struct {
	Status string `json:"status"`
	Route  struct {
		Paths []struct {
			Distance string `json:"distance"`
			Duration string `json:"duration"`
		} `json:"paths"`
	} `json:"route"`
}

func RouteServer() *server.StreamableHTTPServer {
	s := server.NewMCPServer("AMap Navigation", "1.0.0")
	// 请替换为你的高德 Web 服务 Key, 访问开放平台获取: https://console.amap.com/dev/key/app
	amapKey := os.Getenv("AMAP_WEB_API_KEY")
	if amapKey == "" {
		amapKey = config.Cfg.Amap.WebApiKey
	}
	// 定义工具：骑行路径规划
	routeTool := mcp.NewTool("plan_ebike_route",
		mcp.WithDescription("规划电动车骑行路径，计算距离和时间"),
		mcp.WithString("origin", mcp.Required(), mcp.Description("起点坐标，格式：lon,lat")),
		mcp.WithString("destination", mcp.Required(), mcp.Description("终点坐标，格式：lon,lat")),
		mcp.WithString("waypoints", mcp.Required(), mcp.Description("途径点坐标串，默认支持1个有序途径点。多个途径点坐标按顺序以英文分号;分隔。最大支持16个途经点。")),
	)

	s.AddTool(routeTool, func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
		args, ok := request.Params.Arguments.(map[string]interface{})
		if !ok {
			return mcp.NewToolResultError("Invalid arguments format"), nil
		}
		origin, ok1 := args["origin"].(string)
		dest, ok2 := args["destination"].(string)
		way, ok2 := args["waypoints"].(string)
		if !ok1 || !ok2 {
			return mcp.NewToolResultError("Missing required params: origin or destination"), nil
		}
		url := fmt.Sprintf("https://restapi.amap.com/v5/direction/driving?key=%s&origin=%s&destination=%s&waypoints=%s&show_fields=cost&strategy=38", amapKey, origin, dest, way)
		resp, err := http.Get(url)
		if err != nil {
			return mcp.NewToolResultError(fmt.Sprintf("API request failed: %v", err)), nil
		}
		defer func(Body io.ReadCloser) {
			if err := Body.Close(); err != nil {
				log.Fatal(err)
			}
		}(resp.Body)

		body, _ := io.ReadAll(resp.Body)
		var amapResp AmapRouteResponse
		if err = json.Unmarshal(body, &amapResp); err != nil {
			return nil, err
		}

		if amapResp.Status != "1" || len(amapResp.Route.Paths) == 0 {
			return mcp.NewToolResultText(fmt.Sprintf("无法规划路径: %s", string(body))), nil
		}

		path := amapResp.Route.Paths[0]
		result := fmt.Sprintf("从 %s 到 %s 的骑行规划:\n距离: %s 米\n预计耗时: %s 秒", origin, dest, path.Distance, path.Duration)

		return mcp.NewToolResultText(result), nil
	})
	// 4. 启动服务, 采用流式(Streamable), 也可以使用STDIO(server.ServeStdio)
	return server.NewStreamableHTTPServer(s,
		server.WithHeartbeatInterval(30*time.Second),
		server.WithStateful(true),
	)
}
